/** 
* All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
* 
* BaseTeamInfoService
* 团队信息
* 
* 修改纪录
* 2020-08-27 版本：1.0 jiangtao 创建。
* @version 版本：1.0
* @author 作者：jiangtao
* 创建日期：2020-08-27
*/
package com.topscomm.base.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.topscomm.base.BaseSystemConst;
import com.topscomm.base.pojo.BaseTeamInfoEntity;
import com.topscomm.base.pojo.BaseTeamRelationEntity;
import com.topscomm.base.pojo.BaseTeamUserEntity;
import com.topscomm.base.service.IBaseTeamInfoService;
import com.topscomm.base.service.impl.auto.BaseTeamInfoServiceAuto;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;

@Service(value = "baseTeamInfoService")
@Scope(value = "singleton")
public class BaseTeamInfoService extends BaseTeamInfoServiceAuto implements IBaseTeamInfoService {
	@Resource(name = "baseTeamRelationService")
	private BaseTeamRelationService baseTeamRelationService;
	@Resource(name = "baseTeamUserService")
	private BaseTeamUserService baseTeamUserService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> doSave(Map<String, Object> inputMap) {
		long id = ConvertUtil.convertToLong(inputMap.get("id"));
		BaseTeamInfoEntity baseTeamInfoEntity = new BaseTeamInfoEntity();
		baseTeamInfoEntity.convertFromMap(inputMap);
		List<BasicEntity> basicEntities = new ArrayList<BasicEntity>();
		if (id <= 0) {
			// 执行新增操作
			long[] arrayId = PrimaryKeyUtil.GeneIDs(baseTeamInfoEntity.getTableName(), 1);
			baseTeamInfoEntity.setId(arrayId[0]);
			this.insert(baseTeamInfoEntity);
		} else {
			this.updateEntity(baseTeamInfoEntity);
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendLineSingle("teamid = {0} or subteamid = {0}", baseTeamInfoEntity.getId());
			baseTeamRelationService.deleteByWhere(sql.toString());
		}
		if (inputMap.containsKey("highteam")) {
			String highteam = ConvertUtil.convertToString(inputMap.get("highteam"));
			if (!StringUtil.isEmpty(highteam)) {
				String[] highteamArray = highteam.split(",");
				if (highteamArray != null) {
					for (String highteamTemp : highteamArray) {
						BaseTeamRelationEntity relationEntity = new BaseTeamRelationEntity();
						relationEntity.setTeamid(ConvertUtil.convertToLong(highteamTemp));
						relationEntity.setSubteamid(baseTeamInfoEntity.getId());
						basicEntities.add(relationEntity);
					}
				}

			}
		}
		// 直接上级，直接设置下级为每个团队id,团队为本次插入团队id
		if (inputMap.containsKey("lowteam")) {
			String lowteam = ConvertUtil.convertToString(inputMap.get("lowteam"));
			if (!StringUtil.isEmpty(lowteam)) {
				String[] lowteamArray = lowteam.split(",");
				if (lowteamArray != null) {
					for (String lowteamTemp : lowteamArray) {
						BaseTeamRelationEntity relationEntity = new BaseTeamRelationEntity();
						relationEntity.setSubteamid(ConvertUtil.convertToLong(lowteamTemp));
						relationEntity.setTeamid(baseTeamInfoEntity.getId());
						basicEntities.add(relationEntity);
					}
				}
			}
		}
		if (basicEntities.size() > 0) {
			baseTeamRelationService.insertBatch(basicEntities);
		}
		inputMap.put("id", baseTeamInfoEntity.getId());
		return inputMap;
	}

	@Override
	protected void deleteBefore(String whereSql) {
		super.deleteBefore(whereSql);
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" teamid in (select id from {0} where {1} ) or subteamid in ( select id from {0} where {1}  )",
				BaseTeamInfoEntity.tableName, whereSql);
		baseTeamRelationService.deleteByWhere(sql.toString());
		sql.clear();
		sql.appendSingle(" teamid in (select id from {0} where {1} )", BaseTeamInfoEntity.tableName, whereSql);
		baseTeamUserService.deleteByWhere(sql.toString());

	}

	/**
	 * 获取某一团队下的所有下属团队
	 * 
	 * @author: jiangtao
	 * @date: 2020年8月27日上午9:12:10
	 * @params:
	 * @return_type: void
	 * @description:
	 * @modify:
	 */
	private void getChildNode(List<Map<String, Object>> baseTeamRelationEntities, long teamid, List<Long> finalLong) {
		List<Long> partLong = new ArrayList<Long>();
		for (Map<String, Object> relationEntity : baseTeamRelationEntities) {
			if (ConvertUtil.convertToLong(relationEntity.get("teamid")) == teamid) {
				partLong.add(ConvertUtil.convertToLong(relationEntity.get("subteamid")));
			}
		}
		if (partLong != null && partLong.size() > 0) {
			for (int i = 0; i < partLong.size(); i++) {
				finalLong.add(partLong.get(i));
				getChildNode(baseTeamRelationEntities, partLong.get(i), finalLong);
			}
		}
	}

	/**
	 * 获取用户所在团队角色和团队下级团队
	 * 
	 * @author: jiangtao
	 * @date: 2020年8月27日上午9:15:57
	 * @params:
	 * @return_type: List<Map<String,Object>>
	 * @description:
	 * @modify:
	 */
	public List<Map<String, Object>> getChildrenTeams(String usercode) {
		// 如果工号为空，直接返回
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		if (StringUtil.isEmpty(usercode)) {
			return result;
		}
		BaseTeamRelationService baseTeamRelationService = (BaseTeamRelationService) SpringUtil
				.getBean("baseTeamRelationService");
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("select teamid,usertype,positionbegintime from BaseTeamUser where usercode = '{0}'", usercode);
		List<Map<String, Object>> userTeams = this.selectExecute(sql.toString());
		if (userTeams != null && userTeams.size() > 0) {
			// 如果该对应用户在某一个团队中，查询关系
			List<String> queryFields = new ArrayList<>();
			queryFields.add(BaseTeamRelationEntity.FieldTeamid);
			queryFields.add(BaseTeamRelationEntity.FieldSubteamid);
			List<Map<String, Object>> teamRelationMaps = baseTeamRelationService.queryMapFieldsByWhere(" 1= 1",
					queryFields);
			for (Map<String, Object> userTeam : userTeams) {
				Map<String, Object> map = new HashMap<>();
				// usertype 为该用户在团队中的角色
				map.put("usertype", ConvertUtil.convertToString(userTeam.get("usertype")));
				map.put("teamid", ConvertUtil.convertToString(userTeam.get("teamid")));
				map.put("positionbegintime", ConvertUtil.convertToString(userTeam.get("positionbegintime")));
				List<Long> finalLong = new ArrayList<Long>();
				long teamId = ConvertUtil.convertToLong(userTeam.get("teamid"));
				getChildNode(teamRelationMaps, teamId, finalLong);
				// 添加团队自身
				finalLong.add(teamId);
				String childTeams = String.join(",",
						finalLong.stream().map(String::valueOf).collect(Collectors.toList()));
				// childteams为其可以查看的团队
				map.put("childteams", childTeams);
				result.add(map);
			}
		}
		return result;
	}

	@Override
	public List<Map<String, Object>> getTeamMembers(String teamIds) {
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		if (StringUtil.isEmpty(teamIds)) {
			return result;
		}
		List<String> queryFields = new ArrayList<>();
		queryFields.add(BaseTeamUserEntity.FieldTeamid);
		queryFields.add(BaseTeamUserEntity.FieldUsercode);
		queryFields.add(BaseTeamUserEntity.FieldUsername);
		queryFields.add(BaseTeamUserEntity.FieldDeptid);
		queryFields.add(BaseTeamUserEntity.FieldUsertype);
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" teamid in ({0})", teamIds);
		result = baseTeamUserService.queryMapFieldsByWhere(sql.toString(), queryFields);
		return result;
	}

	/**
	 * @description: 得到用户所在的团队
	 * @param userCode
	 * @return
	 * @author: donghang
	 * @date: 2020年9月1日下午5:34:55
	 * @modify:
	 */
	@Override
	public Map<String, Object> getUserTeam(String userCode) {
		// 查询人员所在的团队，子团队id(包含本身)放在childteams中
		List<Map<String, Object>> teamList = this.getChildrenTeams(userCode);
		// 查询当前人员团队和级别 Key：团队id,进行去重处理
		Map<String, Object> userTeamMap = new HashMap<>();
		for (Map<String, Object> teamMap : teamList) {
			String teamId = ConvertUtil.convertToString(teamMap.get("teamid"));
			String userType = ConvertUtil.convertToString(teamMap.get("usertype"));
			String positionBegintime = ConvertUtil.convertToString(teamMap.get("positionbegintime"));
			String childTeamIds = ConvertUtil.convertToString(teamMap.get("childteams"));
			if (userTeamMap.containsKey(teamId)) {
				Map<String, Object> oldMap = (Map<String, Object>) userTeamMap.get(teamId);
				String oldUserType = ConvertUtil.convertToString(oldMap.get("usertype"));
				// 如果先前是主任
				if (BaseSystemConst.TeamUserTypeEnum.Director.equals(oldUserType)) {
					userType = BaseSystemConst.TeamUserTypeEnum.Director;
					positionBegintime = ConvertUtil.convertToString(oldMap.get("positionbegintime"));
				} else if (!BaseSystemConst.TeamUserTypeEnum.Director.equals(oldUserType)
						&& !BaseSystemConst.TeamUserTypeEnum.Director.equals(userType)) {
					// 如果先前不是主任，现在也不是主任，比较授权时间，取授权时间较长的作为该团队角色的最新授权时间
					Date oldPositionBegintime = ConvertUtil.convertToDate(oldMap.get("positionbegintime"));
					Date nowPositionBegintime = ConvertUtil.convertToDate(positionBegintime);
					if (nowPositionBegintime.compareTo(oldPositionBegintime) > 0) {
						positionBegintime = ConvertUtil.convertToString(oldMap.get("positionbegintime"));
					}
				}
			}
			// 孩子团队包含自身
			String[] teamIds = childTeamIds.split(",");
			for (String childId : teamIds) {
				Map<String, Object> chileMap = new HashMap<String, Object>();
				chileMap.put("teamid", childId);
				chileMap.put("positionbegintime", positionBegintime);
				chileMap.put("usertype", userType);
				if (userType.equals(BaseSystemConst.TeamUserTypeEnum.Director)) {
					chileMap.put("usertype", BaseSystemConst.TeamUserTypeEnum.Director);
				}
				userTeamMap.put(childId, chileMap);
			}
		}
		return userTeamMap;
	}
}
